﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using Model;
using Resources;
using Service;

public partial class workOrderSub : System.Web.UI.Page
{
    private int _NumberRow = 0;
    WorkOrderService _WorkOrderService  = new WorkOrderService();
    WODirectService _WODirectService = new WODirectService();
    Utility _Utility  = new Utility();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (!new Utility().TestPermissions(Resource.PermissionDeleteWorkOrderTask))
            {
                lblMessageValidate1.Text = Resource.Permission;
                pnlBody.Visible = false;
                pnlPlanning.Visible = false;
                pnlViewPlanning.Visible = false;
                return;
            }

            txtHiddenTaskId.Text = Request.QueryString["taskId"];
            pnlBody.Visible = false;
            pnlPlanning.Visible = false;
            if ((Request.QueryString["delete"] != null))
                DeleteTaskInWorkOrder(new Utility().ConvertToInteger(Request.QueryString["taskId"]));
            DisplayDetailTasksInWorkORDER();
        }
    }
    private void DeleteTaskInWorkOrder(int taskId)
    {
        WorkOrderService _WorkOrderService = new WorkOrderService();
        _WorkOrderService.DeleteTaskWorkOrder(_WorkOrderService.GetTaskWorkOrder(taskId));
        

    }
    private void DisplayDetailTasksInWorkORDER()
    {
            int workOrderId = new Utility().ConvertToInteger(Request.QueryString["workOrderId"]);
            int taskId = new Utility().ConvertToInteger(Request.QueryString["taskId"]);

            if(taskId != 0 )
            {
                if (grdWorkOrderTask.Rows.Count != 0)
                {
                    if (Request.QueryString["detail"] != null)
                    {
                        pnlBody.Visible = true;
                        lblCodeNumber.Text = "Detail information of task Nº : " + taskId;
                        GetTaskDetail(workOrderId, taskId);
                    }
                    else if (Request.QueryString["addPlanning"] != null)
                    {
                        pnlPlanning.Visible = true;
                        lblPlanning.Text = Resource.MsgPlanningAddInformation + txtHiddenTaskId.Text;

                    } 
                    if (Request.QueryString["viewPlanning"] != null)
                    {
                        if (!new Utility().TestPermissions(Resource.PermissionViewPlanningTask))
                        {
                            lblMessageValidate2.Text = Resource.Permission;
                            return;
                        }
                        pnlViewPlanning.Visible = true;
                        
                    }

                }
                else pnlBody.Visible = false;

            }else pnlBody.Visible = false;
            
         
    }
    protected void grdEquipment_RowCommand(object sender, GridViewCommandEventArgs e)
    {
       
       
    }
    public int GetTabIndex()
    {
        int tabIndex = Request.QueryString["tabIndex"] != null
                        ?
                            Int32.Parse(Request.QueryString["tabIndex"])
                        : 0;
        if (Session["defaultTabIndex"] != null)
        {
            tabIndex = Int32.Parse(Session["defaultTabIndex"].ToString());
            Session["defaultTabIndex"] = null;
        }

        return tabIndex;
    }
    protected void grdEquipment_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdWorkOrderTask.PageIndex = e.NewPageIndex;
        txtHiddenPageIndex.Text = grdWorkOrderTask.PageIndex.ToString();
        Session["pageIndex"] = grdWorkOrderTask.PageIndex;
    }
    public int GetPageIndex()
    {
        return Session["pageIndex"] != null
                   ?
                       Int32.Parse(Session["pageIndex"].ToString())
                   : 0;
    }
    protected void grdEquipment_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grdWorkOrderTask.EditIndex = -1;
    }
    protected void grdEquipment_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grdWorkOrderTask.EditIndex = e.NewEditIndex;
    }
    protected void grdEquipment_SelectedIndexChanged1(object sender, EventArgs e)
    {

    }
    protected void grdEquipment_RowDataBound1(object sender, GridViewRowEventArgs e)
    {
        //_NumberRow = (grdWorkOrderTask.PageCount -1)* grdWorkOrderTask.PageSize
        //GridViewRow row = grdWorkOrderTask.Rows[grdWorkOrderTask.PageCount - 1];
        
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            
            e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";
            e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
        }



    }
    protected void grdEquipment_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void grdEquipment_Sorted(object sender, EventArgs e)
    {
        grdWorkOrderTask.DataBind();
    }
    protected void grdWorkOrderTask_Sorting(object sender, GridViewSortEventArgs e)
    {

    }
    protected void odsTask_Selected(object sender, ObjectDataSourceStatusEventArgs e)
    {
        if (e.ReturnValue != null)
        {
            lblTotalEquipment.Text = "Sub tasks of work order Nº" + Session["workOrderId"] + " : "
                +((DataTable)e.ReturnValue).Rows.Count.ToString();
            grdTemporary.Visible = ((DataTable)e.ReturnValue).Rows.Count == 0 ? true : false;

        }
    }
    
    private WorkOrderTask GetWorkOrderTask(int workOrderId, int problemId, string problem)
    {
        WorkOrderTask workOrderTask = new WorkOrderTask();
        workOrderTask.RequiredDate = _Utility.ConvertToCustomizedFormat(txtRequiredDate.txtDate.Text);
        workOrderTask.EquipmentCodeNumber = txtEquipmentID.Text;
        workOrderTask.ProblemId = problemId;
        workOrderTask.WorkOrderId = workOrderId;
        workOrderTask.IsCancel = false;
        workOrderTask.ProposedProblem = problem;
        workOrderTask.WorkOrderTaskId = _Utility.ConvertToInteger(Request.QueryString["taskId"]);
        return workOrderTask;

    }
    private bool ValidateData()
    {
        

        if (drlProblem.SelectedIndex == -1)
        {
            lblRequiredDepartment.Text = Resource.MessInformSelectAValue;
            return false;
        }

        lblRequiredDepartment.Text = string.Empty;

        if (String.IsNullOrEmpty(txtRequiredDate.txtDate.Text))
        {
            lblRequiredRequestDate.Text = Resource.MsgFillInformation;
            return false;
        }
        lblRequiredRequestDate.Text = string.Empty;
        return true;
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        ClearWorkOrder();
    }
    private void GetTaskDetail  (int workOrderId,int taskId)
    {

        WorkOrderTask task = _WorkOrderService.GetWorkOrderTasks(workOrderId, taskId);
        txtEquipmentID.Text = task.EquipmentCodeNumber;
        DataTable rowFound = _WODirectService.IsCodeNumberExist(txtEquipmentID.Text);
        
        lblInformation.Text = string.Empty;
        if(rowFound.Rows.Count != 0)

        txtHiddenEquipmentType.Text = rowFound.Rows[0]["typeEquipementID"].ToString();
        
        if (!String.IsNullOrEmpty(task.EquipmentCodeNumber)){

            drlProblem.DataSource =
                    new ReferenceDataDirectService().GetProblemByTypeEquipmentId(_Utility.ConvertToInteger(txtHiddenEquipmentType.Text));
            drlProblem.DataValueField = "GROUPEPROBLEMID";
            drlProblem.DataTextField = "GROUPEPROBLEM";
            drlProblem.DataBind();
        }

        txtNewProblem.Text = task.ProposedProblem;
        txtWorkOrder.Text = task.WorkOrderId.ToString();
        drlProblem.SelectedValue = task.ProblemId.ToString();
        txtRequiredDate.txtDate.Text = UitilityService.ConvertDateToString(task.RequiredDate, Resource.DateEnglishFormat);

    }
    protected void txtEquipmentID_TextChanged(object sender, EventArgs e)
    {
       
    }
    private void ClearWorkOrder()
    {
        txtRequiredDate.txtDate.Text = string.Empty;
        txtNewProblem.Text = string.Empty;
        drlProblem.SelectedIndex = -1;
    }
    protected void btnValidate_Click(object sender, EventArgs e)
    {

        if (!new Utility().TestPermissions(Resource.PermissionEditWorkOrderTask))
        {
            lblMessageValidate.Text = Resource.Permission;
            DisplayDetailTasksInWorkORDER();
            return;
        }
        try
        {

            if (!ValidateData()) return;
            //add new problem if not exist
            Problem problem = new Problem();
            if (!String.IsNullOrEmpty(txtNewProblem.Text))
            {
                int groupProbId = new Utility().ConvertToInteger(drlProblem.SelectedValue);
                problem = _WorkOrderService.IsAlreadyExistProblem(groupProbId, txtNewProblem.Text);
                
                if (problem.ProblemId == 0)
                {
                    problem.GroupProblemId = groupProbId;
                    problem.ProblemLabel = txtNewProblem.Text;
                    _WorkOrderService.SaveProblem(problem);
                }
            }

            // add  taskInworkorder
            WorkOrderTask workOrderTask = GetWorkOrderTask(_Utility.ConvertToInteger(Request.QueryString["workOrderId"]), problem.ProblemId, problem.ProblemLabel);
            _WorkOrderService.SaveWorkOrderTask(workOrderTask);

        }
        catch (Exception ex)
        {
            lblInformation.Text = ex.Message;
            throw ex;
        }
    }

    protected void btnValidateWorkOrder_Click(object sender, EventArgs e)
    {

        if (!new Utility().TestPermissions(Resource.PermissionAddPlanningTask))
        {
            lblMessageValidateAdd.Text = Resource.Permission;
            ClearWorkOrderFields();
            return;
        }
        try
        {
            if (drlITStaff.SelectedIndex != 0)
            {
                Utility _Utility = new Utility();

                Planning planning = GetPlanning(_Utility.ConvertToInteger(txtHiddenTaskId.Text));
                planning.PlanningId = _Utility.ConvertToInteger(Request.QueryString["planningId"]);

                new PlanningService().SavePlanning(planning);

                Label1.Text = Resources.Resource.MessageValidate;
                return;

            }
        }
        catch (Exception ex)
        {
            lblInformation.Text = ex.Message;
        }

    }
    private Planning GetPlanning(int taskId)
    {
        Utility _Uitility = new Utility();
        Planning planning = new Planning();

        planning.EmployeeId = Int32.Parse(drlITStaff.SelectedValue);
        planning.EstimateTimeInMinute = !String.IsNullOrEmpty(txtPlanTime.Text) ? _Uitility.ConvertToInteger(txtPlanTime.Text) : 0;
        planning.PlanningDate = _Uitility.ConvertToCustomizedFormat(txtPlanDate.txtDate.Text);

        if (!String.IsNullOrEmpty(txtPlanTime.Text))
            planning.PlanningTime = DateTime.Parse(txtPlanTime.Text);
        else planning.PlanningTime = DateTime.Parse(DateTime.Now.Hour + ":" + DateTime.Now.Minute);

        planning.Priority = Int32.Parse(drlPriority.SelectedValue);
        planning.Remark = txtRemark.Text;
        planning.TaskId = taskId;


        return planning;

    }
    private void ClearWorkOrderFields()
    {
        txtRemark.Text = string.Empty;
        txtPlanTime.Text = string.Empty;
        txtEstimatedTime.Text = string.Empty;
        drlITStaff.SelectedIndex = -1;
        drlPriority.SelectedIndex = -1;
    }
    protected void btnCancelWorkOrder_Click(object sender, EventArgs e)
    {
        ClearWorkOrderFields();
    }
}
